<script lang="ts" setup>
import type { CreateOrUpdateTableRequestData, TableData } from "@@/apis/tables/type"
import type { FormInstance, FormRules } from "element-plus"
import { deleteActivityCommentDataApi, getActivityCommentApi, updateActivityCommentDataApi } from "@@/apis/activity"
import { usePagination } from "@@/composables/usePagination"
import { formatDateTime } from "@/common/utils/datetime.ts"
import { CirclePlus, Delete, Refresh, RefreshRight, Search } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"
import { getToken } from "@@/utils/cache/cookies"

defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})

const route = useRoute()
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// #region 增
const DEFAULT_FORM_DATA: CreateOrUpdateTableRequestData = {
  id: undefined,
  username: "",
  password: ""
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateTableRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<CreateOrUpdateTableRequestData> = {
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  password: [{ required: true, trigger: "blur", message: "请输入密码" }]
}
function handleCreateOrUpdate() {
  formRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过")
      return
    }
    loading.value = true
    const api = formData.value.id === undefined ? createTableDataApi : updateTableDataApi
    api(formData.value).then(() => {
      ElMessage.success("操作成功")
      dialogVisible.value = false
      getTableData()
    }).finally(() => {
      loading.value = false
    })
  })
}
function resetForm() {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
// #endregion

// #region 删
function handleDelete(row?: TableData) {
  const text = row ? "" : "批量"
  ElMessageBox.confirm(`正在${text}删除评论，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const params = {
      comment_id: row ? [row.comment_id] : ids.value,
    }
    deleteActivityCommentDataApi(params).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
// #endregion

// #region 改
function handleUpdate(row: TableData) {
  let foundObjects = []
  let status
  if (!row) {
    foundObjects = tableData.value.filter(obj => obj.comment_id === ids.value[0])
    status = foundObjects[0].status === 1 ? 0 : 1
  } else {
    status = row.status === 1 ? 0 : 1
  }
  const token = getToken()
  const params = {
    token,
    activity_id: '',
    content: '',
    comment_id: row ? [row.comment_id] : ids.value,
    status: status
  }
  updateActivityCommentDataApi(params).then(({ data }) => {
    ElMessage.success("审批审核成功！")
    getTableData()
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    // loading.value = false
  })
}
// #endregion

// #region 查
const tableData = ref<TableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  username: ""
})
const ids = ref<number[]>([])

function getTableData() {
  loading.value = true
  getActivityCommentApi({
    type: 3,
    page: paginationData.currentPage,
    page_size: paginationData.pageSize,
    activity_id: route.query.id
  }).then(({ data }) => {
    paginationData.total = data.total
    tableData.value = data.list
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    loading.value = false
  })
}
// #endregion

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.comment_id)
}

function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}

function formatJson(data) {
  if (data !== '') {
    const row = JSON.parse(data)
    return row[0].url
  }
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="关键字">
          <el-input v-model="searchData.username" placeholder="请输入关键字" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">
            新增用户
          </el-button> -->
          <el-button type="primary" :icon="CirclePlus" @click="handleUpdate()" :disabled="ids.length < 1">
            批量审核
          </el-button>
          <el-button type="danger" :icon="Delete" @click="handleDelete()" :disabled="ids.length < 1">
            批量删除
          </el-button>
        </div>
        <div>
          <el-tooltip content="刷新评论">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="comment_id" label="用户" align="center" >
            <template #default="scope">
              匿名用户 {{ scope.row.comment_id +1 }}
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容" align="center" />
          <el-table-column prop="file_json" label="图片" align="center">
            <template #default="scope">
              <el-tooltip content="" effect="dark" placement="right" :enterable="true">
                <template v-slot:content>
                  <img v-if="formatJson(scope.row.file_json)" :src="formatJson(scope.row.file_json)" alt="Tooltip Image" style="max-width: 100%; height: auto;" />
                  <span v-else>暂无图片</span>
                </template>
                <el-image  style="width: 30px; height: 30px" :src="formatJson(scope.row.file_json)"  fit="cover" />
              </el-tooltip>

            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" align="center" >
            <template #default="scope">
               <span v-if="scope.row.type === 1">弹幕</span>
               <span v-if="scope.row.type === 2">评论</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
              <el-switch
                :model-value="scope.row.status === 1 ? true : false"
                inline-prompt
                active-text="通过"
                inactive-text="拒绝"
                @change="handleUpdate(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createtime" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createtime * 1000) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <!-- <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">
                修改
              </el-button> -->
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

  </div>
</template>

<style lang="scss" scoped>
.el-alert {
  margin-bottom: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
